package com.example.andylau96.res.Function.Cashier;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.andylau96.res.DataBase.CashierDataBase;
import com.example.andylau96.res.Main.MainActivity;
import com.example.andylau96.res.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by AndyLau96 on 2016/12/19.
 */
public class xiaofeiFragment extends Fragment implements View.OnClickListener,AdapterView.OnItemLongClickListener,AdapterView.OnItemClickListener
{
    private LinearLayout title,tab;
    private Button ok,add,del;
    private ImageButton re;
    private ListView xiaofei_list;
    private SQLiteDatabase db;
    private int index=-1;
    private SimpleAdapter adapter;
    private List<Map<String,Object>> lt;
    private int max=0;
    private EditText text_name,text_price;
    private TextView v,t;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.xiaofei,container,false);
        title= (LinearLayout) view.findViewById(R.id.xiaofei_title);
        tab= (LinearLayout) view.findViewById(R.id.xiaofei_tab);
        xiaofei_list= (ListView) view.findViewById(R.id.xiaofei_list);
        re= (ImageButton) view.findViewById(R.id.xiaofei_title_return);
        ok= (Button) view.findViewById(R.id.xiaofei_title_ok);
        add= (Button) view.findViewById(R.id.xiaofei_add);
        del= (Button) view.findViewById(R.id.xiaofei_del);
        add.setOnClickListener(this);
        del.setOnClickListener(this);
        re.setOnClickListener(this);
        ok.setOnClickListener(this);
        xiaofei_list.setOnItemClickListener(this);
        xiaofei_list.setOnItemLongClickListener(this);
        lt=getData();
        adapter=new SimpleAdapter(getActivity().getApplicationContext(),lt,R.layout.xiaofei_item,new String[]{"id","name","price"},new int[]{
        R.id.xiaofei_id,R.id.xiaofei_name,R.id.xiaofei_price});
        xiaofei_list.setAdapter(adapter);
        return view;
    }

    @Override
    public void onClick(View view) {
        int id=view.getId();
        if(id==R.id.xiaofei_title_ok)
        {
            int i=xiaofei_list.getFirstVisiblePosition();
            LinearLayout temp= (LinearLayout) xiaofei_list.getChildAt(i);
            while(temp!=null)
            {
                TextView name= (TextView) temp.findViewById(R.id.xiaofei_name);
                TextView mid= (TextView) temp.findViewById(R.id.xiaofei_id);
                TextView mprice= (TextView) temp.findViewById(R.id.xiaofei_price);
                String x=name.getText().toString();
                String y=mid.getText().toString();
                String z=mprice.getText().toString();
                db=new CashierDataBase(getActivity().getApplication()).getWritableDatabase();
                db.execSQL("update ConsumeItem set itemName='"+x+"',itemPrice="+z+" where itemID="+y);
                i++;
                temp=(LinearLayout) xiaofei_list.getChildAt(i);
            }
            db.close();
            Toast.makeText(getActivity(),"保存成功",Toast.LENGTH_SHORT).show();
        }
        if(id==R.id.xiaofei_title_return)
        {
            getFragmentManager().popBackStack();
        }
        if(id==R.id.xiaofei_del)
        {
            LinearLayout x= (LinearLayout) xiaofei_list.getChildAt(index);
            TextView y= (TextView) x.findViewById(R.id.xiaofei_id);
            db=new CashierDataBase(getActivity().getApplication()).getWritableDatabase();
            try {
                db.execSQL("delete from ConsumeItem where itemID=" + y.getText().toString());
                db.execSQL("delete from Erji where itemID=" + y.getText().toString());
            }catch(Exception e)
            {
            }
            adapter=new SimpleAdapter(getActivity().getApplicationContext(),getData(),R.layout.xiaofei_item,new String[]{"id","name","price"},new int[]{
                    R.id.xiaofei_id,R.id.xiaofei_name,R.id.xiaofei_price});
            db.close();
            adapter.notifyDataSetChanged();
            xiaofei_list.setAdapter(adapter);
            tab.setVisibility(View.GONE);
            index=-1;
        }
        if(id==R.id.xiaofei_add) {
            tab.setVisibility(View.GONE);
            xiaofei_list.getChildAt(index).setBackgroundColor(Color.parseColor("#ffffff"));
            db = new CashierDataBase(getActivity().getApplication()).getWritableDatabase();
            db.execSQL("insert into ConsumeItem values(" + (max + 1) + ",0.0" + ",'null')");
            db.execSQL("insert into Erji values(" + (++max) + ",0" + ",'null')");
            db.close();
            adapter = new SimpleAdapter(getActivity().getApplicationContext(), getData(), R.layout.xiaofei_item, new String[]{"id", "name", "price"}, new int[]{
                    R.id.xiaofei_id, R.id.xiaofei_name, R.id.xiaofei_price});
            xiaofei_list.setAdapter(adapter);
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
        tab.setVisibility(View.VISIBLE);
        LinearLayout x= (LinearLayout) xiaofei_list.getChildAt(i-xiaofei_list.getFirstVisiblePosition());
        TextView name= (TextView) x.findViewById(R.id.xiaofei_name);
        TextView price= (TextView) x.findViewById(R.id.xiaofei_price);
        adapter.notifyDataSetChanged();
        index=i-xiaofei_list.getFirstVisiblePosition();
        x.setBackgroundColor(Color.parseColor("#00eeee"));
        return true;
    }

    @Override
    public void onStart() {
        super.onStart();
        MainActivity.now=this;
        String theme=null;
        File file=new File("/data/data/com.example.andylau96.res/files/color.txt");
        try {
            InputStreamReader reader=new InputStreamReader(new FileInputStream(file),"UTF-8");
            BufferedReader br=new BufferedReader(reader);
            theme="";
            String temp=null;
            while((temp=br.readLine())!=null)
            {
                theme+=temp;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        title.setBackgroundColor(Color.parseColor(theme));
    }
    public List<Map<String,Object>> getData()
    {
        List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
        db=new CashierDataBase(getActivity().getApplication()).getReadableDatabase();
        Cursor re=db.rawQuery("select *from ConsumeItem",null);
        String name[]=new String[100];
        double price[]=new double[100];
        int id[]=new int[100];
        int i=0;
        re.moveToLast();
        while(!re.isBeforeFirst()) {
            name[i] = re.getString(re.getColumnIndex("itemName"));
            id[i]=re.getInt(re.getColumnIndex("itemID"));
            price[i] = re.getDouble(re.getColumnIndex("itemPrice"));
            if(max<id[i])
            {
                max=id[i];
            }
            Map<String,Object> map=new HashMap<>();
            map.put("id",id[i]);
            map.put("name",name[i]);
            map.put("price",price[i]);
            list.add(map);
            i++;
            re.moveToPrevious();
        }
        re.close();
        db.close();
        return list;
    }
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == event.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (index != -1) {
                LinearLayout x = (LinearLayout) xiaofei_list.getChildAt(index);
                x.setBackgroundColor(Color.parseColor("#ffffff"));
                tab.setVisibility(View.GONE);
                index=-1;
                return true;
            }
            else return false;
        }
        else return false;
     }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        v= (TextView) view.findViewById(R.id.xiaofei_price);
        t=(TextView) view.findViewById(R.id.xiaofei_name);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LinearLayout n= (LinearLayout) getActivity().getLayoutInflater().inflate(R.layout.dailog,null,false);
        text_name = (EditText) n.findViewById(R.id.x);
        text_price= (EditText) n.findViewById(R.id.y);
        text_name.setText(t.getText().toString());
        text_price.setText(v.getText().toString());
        builder.setTitle("请分别输入商品名和单价：");
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setView(n);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String mname=text_name.getText().toString();
                String price=text_price.getText().toString();
                if(mname.length()==0||price.length()==0)
                    Toast.makeText(xiaofeiFragment.this.getActivity(), "请输入完整信息", Toast.LENGTH_SHORT).show();
                else
                {
                    v.setText(price);
                    t.setText(mname);
                    dialogInterface.dismiss();
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }
}
